#include "mysqlConnect.h"
#include <iostream>

MysqlConnect::MysqlConnect(void){
	return;
}

int MysqlConnect::ConnectInit(){
    conn = mysql_init(NULL);
    // 初始化 MySQL 连接
    if (!conn) {
        fprintf(stderr, "mysql_init() failed\n");
        exit(1);
    }


	// 连接到 MySQL 数据库
	if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}
	return 0;
}

MYSQL_RES *MysqlConnect::result(){
	return mysql_store_result(conn);
}

unsigned int MysqlConnect::resultCount(){
	return mysql_num_fields(mysql_store_result(conn));
}

int MysqlConnect::insertSensorData(int farm_id, double co2, double temperature, double humidity, double light, const std::string& time) {
	std::string query = 
		"INSERT INTO env_data (farm_id, co2, temperature, humidity, light_intensity, create_time) VALUES (" +
		std::to_string(farm_id) + ", " + std::to_string(co2) + ", " + std::to_string(temperature) + ", " +
		std::to_string(humidity) + ", " + std::to_string(light) + ", '" + time + "');";

	if (mysql_query(conn, query.c_str())) {
		std::cerr << "Insert failed: " << mysql_error(conn) << "\n";
		return -1;
	}
	return 0;
}

int MysqlConnect::exec(std::string query){
	if (mysql_query(conn, query.c_str())) {
		std::cerr << "exec failed: " << mysql_error(conn) << "\n";
		return -1;
	}
	return 0;
}

bool MysqlConnect::farmIsExist(int farm_id){
	exec("SELECT * FROM farm_info WHERE farm_id="+std::to_string(farm_id));
	bool ret = resultCount() == 0 ? false : true;
	// std::cout << "ID: " << farm_id << " found " << ret << "  SELECT * FROM farm_info WHERE farm_id="+std::to_string(farm_id) << std::endl;
	return ret;
}


MysqlConnect::~MysqlConnect(){
    
	mysql_free_result(res);
	mysql_close(conn);
}